import Router from 'koa-router';
import jwt from 'jsonwebtoken';
import marked from 'marked';

const fs = require('fs');
const path = require('path');
const shell = require('../tools/tools').getShell;
const filename = require('../conf/config').filename;
const shellfile = require('../conf/config').shellfile;
const getDirName = require('../tools/tools').getDirName;

const apiRoute = new Router();

const secret = 'swust';

// login
apiRoute.post('/api/login', ctx => {
    ctx.status = 200;
    const user = ctx.request.body;
    const token = ctx.header.authorization;
    let temp = getDirName(__dirname, filename);
    try {
        let res = shell(`bash ${temp[0]}/${shellfile}`, ['7']);
        let systemUser = res.split('|')[0];
        if (user && user.username && user.username == systemUser) {
            const usertoken = {
                name: user.username,
                password: ('000000' + Math.floor(Math.random() * 999999)).slice(-6)
            };
            const tokens = token.split(' ')[1] || jwt.sign(usertoken, secret, {expiresIn: '10h'});
            ctx.body = {
                code: 1,
                massage: 'LODIN_SUCCESS',
                token: tokens,
                data: usertoken
            };
        } else {
            ctx.body = {
                code: -1,
                data: '',
                massage: 'LODIN_FAIL'
            };
        }
    }
    catch (e) {
        ctx.body = {
            data: '',
            code: -1,
            massage: e
        };
    }
});

// user info
apiRoute.get('/api/user', ctx => {
    const token = ctx.header.authorization;
    if (token) {
        ctx.status = 200;
        let payload = jwt.verify(token.split(' ')[1], secret); // 解密，获取payload
        ctx.body = {
            displayName: payload.name,
            password: payload.password,
            code: 1
        };
    } else {
        ctx.status = 401;
        ctx.body = {
            message: 'token 错误',
            code: -1
        };
    }
});

// labname
apiRoute.get('/api/labname', ctx => {
    ctx.status = 200;
    let temp = getDirName(__dirname, filename);
    if (temp[1].match(/lab/)) {
        ctx.body = {
            labname: temp[1],
            code: 1,
            massage: 'SUCCESS'
        };
    } else {
        ctx.body = {
            labname: '',
            code: -1,
            massage: 'FAIL'
        };
    }
});

// experiment detail
apiRoute.get('/api/labdetail', ctx => {
    ctx.status = 200;
    let temp = getDirName(__dirname, filename);
    try {
        let data = fs.readFileSync(`${temp[0]}/README.md`, 'utf-8');
        ctx.body = {
            data: marked(data),
            code: 1,
            massage: 'SUCCESS'
        };
    }
    catch (e) {
        ctx.body = {
            data: marked('## 本节课暂无实验详情'),
            code: 1,
            massage: e
        };
    }
});

// start docker
apiRoute.get('/api/startexperiment', ctx => {
    ctx.status = 200;
    let token = ctx.header.authorization;
    let temp = getDirName(__dirname, filename);

    let payload = jwt.verify(token.split(' ')[1], secret);
    try {
        let res = shell(`bash ${temp[0]}/${shellfile}`, ['1', payload.password]);
        ctx.body = {
            data: res.replace(/[\r\n]/g, ''),
            code: 1,
            massage: 'SUCCESS'
        };
    }
    catch (e) {
        ctx.body = {
            data: '',
            code: -1,
            massage: 'This experiment is open failed'
        };
    }
});

apiRoute.get('/api/myaddress', ctx => {
    ctx.status = 200;
    let temp = getDirName(__dirname, filename);
    try {
        let res = shell(`bash ${temp[0]}/${shellfile}`, ['4']);
        ctx.body = {
            data: res.replace(/[\r\n]/g, ''),
            code: 1,
            massage: 'SUCCESS'
        };
    }
    catch (e) {
        ctx.body = {
            data: '',
            code: -1,
            massage: e
        };
    }
});

// stop docker
apiRoute.get('/api/stopexperiment', ctx => {
    ctx.status = 200;
    let temp = getDirName(__dirname, filename);
    try {
        let res = shell(`bash ${temp[0]}/${shellfile}`, ['2']);
        ctx.body = {
            data: res.replace(/[\r\n]/g, ''),
            code: 1,
            massage: 'SUCCESS'
        };
    }
    catch (e) {
        ctx.body = {
            data: '',
            code: -1,
            massage: 'This experiment is open failed'
        };
    }
});

// show web info state
apiRoute.get('/api/webinfo', ctx => {
    ctx.status = 200;
    let temp = getDirName(__dirname, filename);
    try {
        let res = shell(`bash ${temp[0]}/${shellfile}`, ['6']);
        let data = res.split('|')[0];
        if (data == false) {
            ctx.body = {
                data: [],
                code: 1,
                massage: 'NOSTART'
            };
        } else {
            ctx.body = {
                data: JSON.parse(data.replace(/[\r\n]/g, '')),
                code: 1,
                massage: 'SUCCESS'
            };
        }
    }
    catch (e) {
        ctx.body = {
            data: [],
            code: -1,
            massage: 'NOSTART'
        };
    }
});

// submit experiment
apiRoute.get('/api/submitexperiment', ctx => {
    ctx.status = 200;
    let temp = getDirName(__dirname, filename);
    let query = ctx.request.query.opt;
    let opt = ['3', '0'];
    query ? opt.push(query) : '';
    try {
        let res = shell(`bash ${temp[0]}/${shellfile}`, opt);
        ctx.body = {
            data: res.replace(/[\r\n]/g, ''),
            code: 1,
            massage: 'SUCCESS'
        };
    }
    catch (e) {
        ctx.body = {
            data: '',
            code: -1,
            massage: e
        };
    }
});

// grade
apiRoute.get('/api/grade', ctx => {
    ctx.status = 200;
    let token = ctx.header.authorization;
    let temp = getDirName(__dirname, filename);
    try {
        let payload = jwt.verify(token.split(' ')[1], secret); // 解密，获取payload
        let res = shell(`cat /home/${payload.name}/linuxer/data/submit/.score/${temp[1]}`);
        res = res.split(/[\r\n]/g);
        let data = [];
        for (let i = 0; i < res.length; i++) {
            res[i] = res[i].split(',');
            if (res[i][0] === payload.name) {
                data.push({
                    name: temp[1],
                    stdnum: res[i][0],
                    teacher: res[i][2],
                    time: res[i][3],
                    grade: res[i][1]
                });
            }
        }
        ctx.body = {
            data: data,
            code: 1,
            massage: 'SUCCESS'
        };
    }
    catch (e) {
        ctx.body = {
            data: [],
            code: -1,
            massage: e
        };
    }
});

apiRoute.post('/api/setting', ctx => {
    ctx.status = 200;
    let token = ctx.header.authorization;
    const user = ctx.request.body;
    if (token && user && user.newkey) {
        try {
            let payload = jwt.verify(token.split(' ')[1], secret); // 解密，获取payload
            const usertoken = {
                name: payload.name,
                password: user.newkey
            };
            const tokens = jwt.sign(usertoken, secret, {expiresIn: '10h'});
            ctx.body = {
                massage: 'SUCCESS',
                token: tokens,
                code: 1
            };
        }
        catch (e) {
            ctx.body = {
                massage: e,
                token: '',
                code: -1
            };
        }
    } else {
        ctx.body = {
            massage: 'ERROR',
            token: '',
            code: -1
        };
    }
});

export default apiRoute;
